package com.hbdl.common.interceptor;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.hbdl.common.utils.IPUtils;
import com.hbdl.web.sys.model.User;
import com.hbdl.web.sys.utils.SysUserUtils;

public class AuthInterceptor implements HandlerInterceptor {

	private final Logger logger = LoggerFactory.getLogger(getClass());
	private Set<String> ignorePath = new HashSet<String>(Arrays.asList("/login", "/captcha", "/notlogin", "/ErrorHandler"));


	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		// request = new ApiHttpServletRequest((HttpServletRequest) request);
		String uri = request.getRequestURI(); // 请求路径
		String ctx = request.getContextPath();
		String path = uri.replace(ctx, "");
//		String value = request.getParameter("value");

		logger.info("请求ip地址："+IPUtils.getClientAddress(request));
		logger.info("请求方法:"+path);
//		logger.info("请求参数:"+value);
		


//		String jsonExchangeError = request.getParameter("jsonExchangeError");
//		if (jsonExchangeError != null && jsonExchangeError.length() > 0) {
//			PrintWriter out = response.getWriter();
//			response.setHeader("Content-type", "text/html;charset=UTF-8");
//			response.setCharacterEncoding("UTF-8");
//			out.print(ResultUtil.getErrorResult(ErrorConstants.JSONCODE.JSON_VALUE_NULL));
//			return false;
//		}
		
		if(!ignorePath.contains(path)){
			
			User sessionUser = SysUserUtils.getSessionLoginUser();
			if(null == sessionUser){
				response.sendRedirect(ctx + "/login");
				return false;
			}
		}
		return true;

	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
